<?php

namespace app\api\controller;

use app\admin\model\store\Servec;
use app\admin\model\Text;
use app\common\controller\Api;
use app\common\model\Follow;
use app\common\model\History;
use app\common\model\OrderComment;
use app\common\model\ServeLabel;
use app\common\model\Store;
use app\common\model\Technician;
use app\common\model\TechnicianServe;
use think\Db;

class Serve  extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];


    /*
     * 服务详情
     */
    public function serve_detail(){
        $uid=$this->auth->id;
        $serve_id=$this->request->request('serve_id');
        if(!$serve_id){
          $this->error('参数不能为空');
        }
        $serve=\app\common\model\Serve::where(['id'=>$serve_id,'is_added'=>0,'serve_status'=>1])->field('id,serve_name,serve_duration,serve_price,serve_image,serve_details,sales,store_id,graphic_details')->find();
        if(!$serve){
          $this->error('服务不存在');
        }
        $technician_ids         = TechnicianServe::where(['serve_id'=>['in',$serve_id],'status'=>1])->group('technician_id')->column('technician_id');
        $technician=Technician::where(['technician_id'=>['in',$technician_ids]])->field('technician_avatar,technician_id')->select();
        foreach ($technician as $k){
            $isset_order=\app\common\model\Order::where(['technician_id'=>$k['technician_id'],'order_status'=>['IN', [2,3,4,5]]])->find();
            if(!empty($isset_order['endserve_time'])){
                $earliestappionent_time = date('H:i', $isset_order['endserve_time']);
            }else{
                $earliestappionent_time = date('H:i', time());
            }
            $k['earliestappionent_time']=$earliestappionent_time;
        }
        $comment=OrderComment::where('serve_id','=',$serve_id)->field('id,uid,star,content,createtime')->select();
        foreach ($comment as $item){
            $item['createtime']=date('Y-m-d H:i',$item['createtime']);
            $item['user']=\app\admin\model\User::where(['id'=>$item['uid'],'postion'=>1])->field('id,nickname,avatar')->find();
        }
        $follow_status=Follow::where(['uid'=>$uid,'serve_id'=>$serve_id,'follow_status'=>1])->find();
        //评论数量
        $comment_count=Db::name('order_comment')->where('serve_id','=',$serve_id)->count();

           if($serve['store_id']==0){
               $tserve=TechnicianServe::where(['serve_id'=>['in',$serve_id],'status'=>1])->group('store_id')->column('store_id');
               $store = Store::where(['store_id'=>['in',$tserve]])->field('store_id,name,feedback,order_rate,store_grade,image')->find()??[];
               if($store){
                   $store['store_grade'] = intval($store['store_grade']);
                   $serve['store'] = $store??[];
               }
               //店铺下面的服务
               $stores = Db::name('technician_serve')->where(['store_id' => ['in', $tserve], 'status' => 1])->group('serve_id')->column('serve_id');
               $store_serve = \app\common\model\Serve::where('id', 'in', $stores)->field('id,serve_name,serve_duration,serve_price,serve_image,store_id')->select();
           }else{
               $store = Store::where(['store_id' =>$serve['store_id']])->field('store_id,name,feedback,order_rate,store_grade,image')->find();
               $store['store_grade'] = intval($store['store_grade']);
               $serve['store'] = $store??[];
               //店铺下面的服务
               $stores = Db::name('technician_serve')->where(['store_id' => ['in', $store['store_id'], 'status' => 1]])->group('serve_id')->column('serve_id');
               $store_serve = \app\common\model\Serve::where('id', 'in', $stores)->field('id,serve_name,serve_duration,serve_price,serve_image,store_id')->select();
           }
        $data=History::create([
            'uid'=>$uid,
            'serve_id'=>$serve_id,
            'createtime'=>time()
        ]);
        $text=Text::where(['id'=>6])->field('id,title,content')->find();

        if($follow_status){
            $serve['follow_status']='已关注';
        }else{
            $serve['follow_status']='未关注';
        }
        $serve['technician']= $technician;
        $serve['comment']= $comment;
        $serve['text']= $text;
        $serve['comment_count']=$comment_count;
        $serve['store_serve']=$store_serve??[];
        $this->success('查询成功',$serve);
    }


    /**
     * 关注服务/取消关注
     */
    public function follow_serve()
    {
        $uid = $this->auth->id;
        $type = $this->request->request('type');//1关注 2取消关注
        $serve_id = $this->request->request('serve_id');
        $postion=$this->auth->postion;
        if($postion!=1){
            $this->error('当前身份不是用户');
        }
        if(!$serve_id){
          $this->error('服务id不能为空');
        }

        if ($type == 1) {
            $serve_info = \app\common\model\Serve::get($serve_id);
            $old_data = Follow::where(['uid' => $uid, 'serve_id' => $serve_id])->find();
            if ($old_data) {
                if ($old_data['follow_status'] == 1) {
                    $this->error('您已关注当前服务');
                } else {
                    $res = $old_data->save(['follow_status' => 1]);
                }
            }else{
                $data = [
                    'uid'               => $uid,
                    'serve_id'     => $serve_id,
                    'serve_name' => $serve_info['serve_name'],
                    'follow_status'     => 1,
                    'follow_time'=>time(),
                    'createtime'        => time(),
                  'type'=>2
                ];
                $res  = Follow::create($data);
            }
            \app\common\model\User::where('id', $uid)->setInc('serve_follow');
        }else if($type==2){
            $serve_info=Follow::where(['uid'=>$uid,'serve_id'=>$serve_id,'follow_status'=>1])->find();
            if(!$serve_info){
                $this->error('你未关注当前服务');
            }
            $res= $serve_info->save(['follow_status' => 2]);
            \app\common\model\User::where('id', $uid)->setDec('serve_follow');
        }
        if($res){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }


    /**
     * 服务分类下面的服务项目
     */

    public function CategoryService(){
      $cid=$this->request->request('cid');
      $store_id=$this->request->request('store_id');//服务商筛选
      $price=$this->request->request('price');//价格优先
      $label=$this->request->request('label');//服务标签
      $order=$this->request->request('order');//销量优先
      $distance=$this->request->request('distance');//距离优先
      $fraction=$this->request->request('fraction');//好评排序
      $lat=$this->request->request('lat','');
      $lon=$this->request->request('lon','');
        if ($lat == 'undefined') {
            $lat = 0;
        }
        if ($lon == 'undefined') {
            $lon = 0;
        }
        $where = [];
        if ($cid) {
            $servec = Db::name('servec')->where(['id' => $cid])->find();
            if (!$servec) {
                $this->error('服务类型错误');
            }
          $where['serve_cid']=$cid;
        }
      if($order){
          if ($order == 1) {
              $order = 'sales desc';
          } else {
              $order = 'sales asc';
          }
      }
      if($fraction){
          if($fraction==1){
              $order = 'feedback desc';
          }else{
              $order = 'feedback asc';
          }
      }
      if($distance){
          if ($distance == 1) {
              $order = 'time_label desc';
          } else {
              $order = 'time_label asc';
          }
      }
      if($price){
          if ($price == 1) {
              $order = 'serve_price asc';
          } else {
              $order = 'serve_price desc';
          }
      }
      if($label){
          $where['label']=['in',$label];
      }
      $where['serve_status']=1;
        $where['is_added']=0;
      if($store_id){
         $store_serve=TechnicianServe::where(['store_id'=>$store_id,'status'=>1])->group('serve_id')->column('serve_id');
         $where['id']=['in',$store_serve];
      }
      $serve=\app\common\model\Serve::where($where)->order($order)->field('id,serve_name,serve_image,serve_duration,technician_id,store_id,sales,feedback,label,time_label,serve_details,serve_price')->select();
      if($serve) {

        foreach ($serve as $key => $value) {
            $value['time_label']=$value['time_label']?:"30";
            if(!strpos($value['time_label'],'分钟')){
                $value['time_label']=$value['time_label'].'分钟';
            }
          $value['store'] = Store::where(['store_id' => $value['store_id']])->field('store_id,name')->find();
          $technician_ids = TechnicianServe::where('serve_id', 'in', $value['id'])->group('technician_id')->column('technician_id');
          if ($technician_ids) {
            $technician = Technician::where('technician_id','in',$technician_ids)->field('technician_id,technician_name,technician_avatar,lon,lat')->select();
            if ($technician) {
              $value['technician']=$technician;
              foreach ( $value['technician'] as $item) {
                  $item['distance'] = distance($lon, $lat, $item['lon'], $item['lat']);
              }
            }
          }
        }
      }
      $this->success('',$serve);

    }

    /**
     * 服务标签
     */

    public function Servelabel(){
        $list=ServeLabel::all();
        $this->success('',$list);
    }

    /**
     * 服务商筛选
     */
    public function Storefilter(){
        $list=Store::field('store_id,name,store_grade')->select();
        $this->success('',$list);
    }


    /**
     * 服务分类筛选
     */

    public function Servec(){
        $cid=$this->request->request('cid');//分类id
        $label=$this->request->request('label');//标签
        $where=[];
        if($cid){
            $where['serve_cid']=$cid;
        }
        if($label){
            $where['label']=$label;
        }
        $where['serve_status']=1;
        $list=\app\common\model\Serve::where($where)->field('id,serve_name,serve_image')->select();
        $this->success('',$list);
    }

    /**
     * 热门推荐
     */
    public function  recommend(){
        $cid=$this->request->request('cid');//分类id
        $label=$this->request->request('label');//标签
        $where=[];
        if($cid){
            $where['serve_cid']=$cid;
        }
        if($label){
            $where['label']=$label;
        }
        $where['serve_status']=1;
//        is_recommend
        $recommend=\app\common\model\Serve::where(['is_recommend'=>1,'serve_status'=>1,'is_added'=>0])->order('sales','desc')->field('serve_name,id,serve_image')->select();
        $serve=\app\common\model\Serve::where($where)->field('serve_name,id,serve_image')->select();
        foreach ($recommend as $item){
            $item['serve']=$serve;
        }
        $this->success('',$recommend);
    }

}